import TagGroup from '@/components/TagGroup';
import TextEditor from '@/pages/cues/components/TextEditor';
import UploadDragger from '@/pages/cues/components/UploadDragger';
import { mediaOrganization, saveNeeds } from '@/services/api/api-needs';
import { CheckCircleTwoTone, SendOutlined } from '@ant-design/icons';
import {
  DrawerForm,
  ModalForm,
  ProForm,
  ProFormCascader,
  ProFormDateRangePicker,
  ProFormInstance,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Card, Cascader, Descriptions, Divider, message, Space, Tag } from 'antd';
import Meta from 'antd/es/card/Meta';
import FormItem from 'antd/es/form/FormItem';
import { DefaultOptionType } from 'antd/es/select';
import { DataNode } from 'antd/es/tree';
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import React, { useRef, useState } from 'react';
import { useAccess } from 'umi';

interface EditNeedsReleaseProps {
  data: NeedsData.NeedsDetails;
  onRefurbish: () => void;
}

const EditNeedsRelease: React.FC<EditNeedsReleaseProps> = ({ data, onRefurbish }) => {
  const access = useAccess();
  const { initialState, setInitialState } = useModel('@@initialState');

  const formRef = useRef<ProFormInstance>();

  const [openAddActive, setOpenAddActive] = useState<boolean>();

  const [modalFormOpen, setModalFormOpenState] = useState<boolean>(false);

  /**
   * 推送单位数据
   */
  const [treeMediaOrganizationData, setTreeMediaOrganizationDataState] = useState<DataNode[]>();

  /**
   * 预备Tree结构数据
   * @param data
   */
  function readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = new Array();
    if (data) {
      data.forEach((val) => {
        treeData.push({
          label: val.name,
          value: val.id,
          disabled: val.isFolder === 1 && val.isOrganization === 0 && val.children === undefined,
          children: readyTreeData(val.children as AdminOrganizationData.Organization[]),
        });
      });
    }
    return treeData;
  }

  /**
   * 加载 媒体
   */
  const loadInitMediaOrganization = async () => {
    try {
      const response = await mediaOrganization();
      if (response.code === 0) {
        setTreeMediaOrganizationDataState(readyTreeData(response.data));
      }
    } catch (error) {}
  };
  /**
   * 级联组件 搜索筛选
   * @param inputValue
   * @param path
   * @returns
   */
  const filter = (inputValue: string, path: DefaultOptionType[]) =>
    path.some(
      (option) => (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) > -1,
    );

  return (
    <DrawerForm
      key="drawer_form_edit_needs_release"
      title="修改发布"
      drawerProps={{
        destroyOnClose: true,
        width: 800,
        maskClosable: false,
      }}
      formRef={formRef}
      trigger={
        <Button
          key="button_edit_needs_release"
          icon={<SendOutlined />}
          type="primary"
          style={{
            background: '#87d068',
          }}
        >
          修改发布
        </Button>
      }
      initialValues={{
        initiateOrganization: data.initiateOrganization,
        name: data.name,
        interviewees: data.interviewees,
        interviewTimes: data.interviewTimes,
        location: data.location,
        content: data.content,
        attachments: data.attachments,
      }}
      open={openAddActive}
      onOpenChange={(visible) => {
        setOpenAddActive(visible);
        if (visible) {
          loadInitMediaOrganization();
        } else {
        }
      }}
      layout="horizontal"
      submitter={{
        render: (props, defaultDoms) => {
          return [
            <Button onClick={() => setOpenAddActive(false)}>取消</Button>,
            <Button
              key="button_add_interview"
              icon={<SendOutlined />}
              type="primary"
              style={{
                background: '#87d068',
              }}
              onClick={() => {
                /**
                 * ======================
                 * 直接发布
                 * ======================
                 */
                const values = formRef.current?.getFieldsValue();

                console.log('====', values);

                if (
                  !(
                    values.initiateOrganization !== undefined &&
                    values.initiateOrganization.length > 0
                  )
                ) {
                  message.warning('请输入发起单位');
                  return;
                }

                if (!(values.contacts && values.contacts.length > 0)) {
                  message.warning('请添加至少一个联络人');
                  return;
                } else {
                  let required = false;

                  values.contacts.forEach((element: { name: any; phone: any }) => {
                    console.log('====', element);
                    if (element.phone == undefined || element.phone.length == 0) {
                      required = true;
                    }
                  });

                  if (required) {
                    message.warning('请补充联络人信息');
                    return;
                  }
                }

                if (!(values.managers && values.managers.length > 0)) {
                  message.warning('请添加至少一个审批意见');
                  return;
                }

                if (!values.name) {
                  message.warning('请输入采访主题');
                  return;
                }

                if (!(values.interviewees && values.interviewees.length > 0)) {
                  message.warning('请添加至少一个采访主体');
                  return;
                }

                if (!(values.assignOrganizationIds && values.assignOrganizationIds.length > 0)) {
                  message.warning('请选择至少一个采访媒体');
                  return;
                }

                if (!(values.interviewTimes && values.interviewTimes.length > 0)) {
                  message.warning('请选择采访时间');
                  return;
                }

                if (!values.location) {
                  message.warning('请输入采访地点');
                  return;
                }

                if (!(values.content !== undefined && values.content.length > 0)) {
                  message.warning('请输入采访内容');
                  return;
                }

                setModalFormOpenState(true);
              }}
            >
              提交
            </Button>,
            <ModalForm
              key={'modal_form_add_interview'}
              title={
                <>
                  <CheckCircleTwoTone
                    style={{
                      marginRight: 8,
                    }}
                    twoToneColor="#87d068"
                  />
                  确认提交
                </>
              }
              autoFocusFirstInput
              modalProps={{
                width: 400,
                destroyOnClose: true,
              }}
              open={modalFormOpen}
              onOpenChange={setModalFormOpenState}
              submitTimeout={2000}
              submitter={{
                submitButtonProps: {
                  type: 'primary',
                  style: { background: '#87d068' },
                },
              }}
              onFinish={async () => {
                const values = formRef.current?.getFieldsValue();

                if (values.attachments !== undefined && values.attachments.length > 0) {
                  values.attachmentIds = values.attachments.map(
                    (item: { response: { data: { id: any } } }) => {
                      return item.response.data.id;
                    },
                  );
                }

                values.interviewTimes = values.interviewTimes.map((item: any) =>
                  dayjs(item).format('YYYY-MM-DD HH:mm:ss'),
                );

                const response = await saveNeeds({
                  ...values,
                  createdSource: 1,
                });

                if (response.code === 0) {
                  message.success('提交成功');
                  setOpenAddActive(false);
                  onRefurbish();
                  return true;
                } else {
                  return false;
                }
              }}
            />,
          ];
        },
      }}
    >
      <Descriptions>
        <Descriptions.Item label="创建单位">{data?.createdOrganizationName}</Descriptions.Item>
        <Descriptions.Item label="创建人">{data?.createdAccountName}</Descriptions.Item>
        <Descriptions.Item label="创建时间">
          {dayjs(data?.createdTime).format('YYYY-MM-DD')}
        </Descriptions.Item>
      </Descriptions>
      <Descriptions>
        <Descriptions.Item span={3} label="联络方式">
          <Space size={[8, 16]} wrap>
            {data?.contacts &&
              data?.contacts.map((item) => (
                <Card
                  style={{ width: 150 }}
                  bodyStyle={{
                    paddingTop: '10px',
                    paddingBottom: '10px',
                  }}
                >
                  <Meta
                    title={
                      <>
                        <Tag style={{ fontSize: 14, marginRight: 5 }}>{item.name}</Tag>
                      </>
                    }
                    description={item.phone}
                  />
                </Card>
              ))}
          </Space>
        </Descriptions.Item>
      </Descriptions>
      <Descriptions>
        <Descriptions.Item span={3} label="审批意见">
          <Space size={[8, 16]} wrap>
            {data?.managers &&
              data?.managers.map((item) => (
                <Card
                  style={{ width: access.媒体采访x配置x管理员 ? 500 : 350 }}
                  bodyStyle={{
                    paddingTop: '10px',
                    paddingBottom: '10px',
                  }}
                >
                  <Meta
                    title={
                      <>
                        <Tag style={{ fontSize: 14, marginRight: 5 }}>{item.name}</Tag>
                        <Tag style={{}}>{item.position}</Tag>
                      </>
                    }
                    description={item.instructions}
                  />
                </Card>
              ))}
          </Space>
        </Descriptions.Item>
      </Descriptions>

      <Divider
        orientation="left"
        style={{
          fontSize: 14,
          fontWeight: 'bold',
        }}
      >
        采访内容
      </Divider>
      <ProFormText
        width="xl"
        name="name"
        label="采访主题"
        required={true}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />
      <ProForm.Item
        label="采访主体"
        name="interviewees"
        required={true}
        extra="输入单位或个人，最少输入一个"
      >
        <TagGroup addText={'点击新增'} />
      </ProForm.Item>

      <ProFormCascader
        width="xl"
        label="采访媒体"
        name="assignOrganizationIds"
        placeholder="选择媒体"
        required={true}
        fieldProps={{
          options: treeMediaOrganizationData,
          showSearch: { filter },
          multiple: true,
          removeIcon: true,
          allowClear: true,
          maxTagCount: 'responsive',
          showCheckedStrategy: Cascader.SHOW_CHILD,
        }}
      />

      <ProFormDateRangePicker
        name="interviewTimes"
        label="采访时间"
        allowClear
        required={true}
        width="xl"
        fieldProps={{
          allowClear: true,
          format: 'YYYY-MM-DD',
          disabledDate: (current) => {
            return current && current < dayjs().endOf('day');
          },
        }}
        extra="需求方期望的采访开始时间与结束时间"
      />

      <ProFormTextArea
        width="xl"
        name="location"
        label="采访地点"
        required={true}
        fieldProps={{
          allowClear: true,
          maxLength: 200,
        }}
      />

      <ProForm.Item name="content" required={true} label="采访内容">
        <TextEditor
          onInit={(editor) => {}}
          readonly={false}
          onClick={(value) => {}}
          defaultContent=""
          tinyID="tinyId"
        />
      </ProForm.Item>
      <FormItem
        name="attachments"
        label={
          <span
            style={{
              marginLeft: 11,
            }}
          >
            附件
          </span>
        }
      >
        <UploadDragger
          style={{
            marginLeft: '28px',
          }}
          onPreview={(file) => {}}
          access={{
            isPicture: access.主动报送x报送线索x附件x图片,
            isVideo: access.主动报送x报送线索x附件x视频,
            isOffice: access.主动报送x报送线索x附件x办公,
            isOther: access.主动报送x报送线索x附件x其他,
          }}
          url="/cues/interview/attachment/save"
          mode="interview"
        />
      </FormItem>
    </DrawerForm>
  );
};
export default EditNeedsRelease;
